package com.fmi.timedealer.plan;

import java.text.DecimalFormat;
import java.util.ArrayList;

import com.fmi.timedealer.R;
import com.fmi.timedealer.R.drawable;
import com.fmi.timedealer.R.id;
import com.fmi.timedealer.R.layout;
import com.fmi.timedealer.R.menu;
import com.fmi.timedealer.datamanager.IDataManager;
import com.fmi.timedealer.datamanager.SQLiteDataManager;
import com.fmi.timedealer.notifications.NotificationReceiver;

import android.app.ListActivity;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;

public class PlanPlannedActivity extends ListActivity {
	
	public final static String PLANNED_ACTIVITY_BUNDLE_KEY = "PlanActivityObject";
	public final static String PLANNED_ACTIVITY_NAME_BUNDLE_KEY = "PlanActivityName";
	
	private static final int ACTION_REQUES_CODE = 0;
	private static final int ACTIVITY_STATUS_LIMIT = 70;	// percentage
	
	private ArrayList<PlannedActivity> activities = null;
	private IDataManager dbManager = null;
	private PlannedActivityAdapter adapter = null;
	private int currentPlanId = 0;
	private boolean comeFromNotification = false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.planned);
		
		dbManager = new SQLiteDataManager("MyDB", this);
		
		Bundle extras = getIntent().getExtras();
		comeFromNotification = extras.getBoolean(NotificationReceiver.NOTIFICATION_EXTRA_KEY, false);
		
		if (comeFromNotification) {
			String ns = Context.NOTIFICATION_SERVICE;
			NotificationManager mNotificationManager = (NotificationManager)getApplicationContext().getSystemService(ns);
			mNotificationManager.cancel(NotificationReceiver.NOTIFICATION_ID);
			
			String planIds = extras.getString(NotificationReceiver.NOTIFICATION_EXTRA_ACTIVITIES_KEY);
			if (planIds != null) {
				activities = getNotificationActivities(planIds.split(","));
			}
			else {
				activities = new ArrayList<PlannedActivity>();
			}
		}
		else {
			currentPlanId = extras.getInt(PLANNED_ACTIVITY_BUNDLE_KEY, 0);
			String currentPlanName = extras.getString(PLANNED_ACTIVITY_NAME_BUNDLE_KEY);
			if (currentPlanName != null && !currentPlanName.equals("")) {
				this.setTitle(this.getTitle() + " for " + currentPlanName);
			}
			
			activities = dbManager.getPlannedActivities(currentPlanId);
		}
		
		refreshAdapter();
	}
	
	private void refreshAdapter() {
		adapter = new PlannedActivityAdapter(this, R.layout.planned_row, activities);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		setListAdapter(adapter);
		
		ListView lv = getListView();
		registerForContextMenu(lv);
		
		adapter.notifyDataSetChanged();
	}
	
	@Override
	public void onResume() {
		super.onResume();
		refreshAdapter();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		if (!comeFromNotification) {
			MenuInflater inflater = getMenuInflater();
			inflater.inflate(R.menu.planned_activities, menu);
		}
	    return true;
    }

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		
		switch (item.getItemId()) {
	        
			case R.id.add_planned_activity: {
	        	Intent i = new Intent(PlanPlannedActivity.this, ManagePlannedActivity.class);
	        	PlannedActivity pa = new PlannedActivity();
	        	pa.setPlanId(currentPlanId);
				i.putExtra(ManagePlannedActivity.ACTIVITY_BUNDLE_KEY, pa);
				startActivityForResult(i, ACTION_REQUES_CODE);
	        	return true;
	        }
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		
		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
		menu.setHeaderTitle(activities.get(info.position).getActivityItem().getName());
		
		MenuInflater inflater = getMenuInflater();
		if (comeFromNotification) {
			inflater.inflate(R.menu.share_plan, menu);
		}
		else {
			inflater.inflate(R.menu.manage_plan, menu);
		}
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
	    
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
	    
		switch (item.getItemId()) {
	        case R.id.edit_plan: {
	        	Intent i = new Intent(PlanPlannedActivity.this, ManagePlannedActivity.class);
				i.putExtra(ManagePlannedActivity.ACTIVITY_BUNDLE_KEY, activities.get(info.position));
				startActivityForResult(i, ACTION_REQUES_CODE);
	        	return true;
	        }
	        case R.id.delete_plan: {
	            deletePlanendActivity(info.position);
	        	return true;
	        }
	        case R.id.share_planned_activity: {
	        	Intent sharingIntent = new Intent(Intent.ACTION_SEND);
	            sharingIntent.setType("text/plain");
	            sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "TimeDealer plans progress");
	            sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, getSharedText(activities.get(info.position)));
	            startActivity(Intent.createChooser(sharingIntent, "Share using"));
	        	return true;
	        }
	        case R.id.share_all_planned_activity: {
	        	Intent sharingIntent = new Intent(Intent.ACTION_SEND);
	            sharingIntent.setType("text/plain");
	            sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "TimeDealer plans progress");
	            sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, getSharedText());
	            startActivity(Intent.createChooser(sharingIntent, "Share using"));
	        	return true;
	        }
	        default:
	            return super.onContextItemSelected(item);
	    }
	}
	
	private String getSharedText(PlannedActivity p) {
		StringBuilder result = new StringBuilder();
		result.append("You are ");
		if (p.getMode() == PlannedActivityMode.POSITIVE) {
			result.append("GOOD");
		}
		else if (p.getMode() == PlannedActivityMode.NEGATIVE) {
			result.append("LATE");
		}
		result.append(" with ");
		result.append(p.getActivityItem().getName());
		result.append(" (");
		result.append(p.getActivityItem().getCategory());
		result.append(").");
		return result.toString();
	}
	
	private String getSharedText() {
		
		StringBuilder result = new StringBuilder();
		ArrayList<PlannedActivity> positive = new ArrayList<PlannedActivity>();
		ArrayList<PlannedActivity> negative = new ArrayList<PlannedActivity>();
		
		for (PlannedActivity activity : activities) {
			if (activity.getMode() == PlannedActivityMode.POSITIVE) {
				positive.add(activity);
			}
			else if (activity.getMode() == PlannedActivityMode.NEGATIVE) {
				negative.add(activity);
			}
		}
		
		if (positive.size() > 0) {
			result.append("You are good with: ");
			for (PlannedActivity activity : positive) {
				result.append(activity.getActivityItem().getName() + ", ");
			}
			result.deleteCharAt(result.length() - 1);
		}
		
		if (negative.size() > 0) {
			result.append("You are late with: ");
			for (PlannedActivity activity : negative) {
				result.append(activity.getActivityItem().getName() + ", ");
			}
			result.deleteCharAt(result.length() - 1);
		}
		
		if (result.length() == 0) {
			result.append("There is no activities for this plan");
		}
		
		return result.toString();
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (requestCode == ACTION_REQUES_CODE) {
			if (resultCode == RESULT_OK) {
				Bundle extras = data.getExtras();
				PlannedActivity item = (PlannedActivity)extras.getSerializable(ManagePlannedActivity.ACTIVITY_BUNDLE_KEY);
				updatePlannedActivity(item);
			}
		}
	}
	
	private ArrayList<PlannedActivity> getNotificationActivities(String[] planIds) {
		
		ArrayList<PlannedActivity> result = new ArrayList<PlannedActivity>();
		
		for (String planId : planIds) {
			
			if (planId == null || planIds.equals("")) {
				continue;
			}
			
			ArrayList<PlannedActivity> activities = dbManager.getPlannedActivities(Integer.parseInt(planId));
			
			int spentTime;
			
			for (PlannedActivity activity : activities) {
				spentTime = dbManager.getTimeSpentForPlannedActivity(activity);
				if (((spentTime * 100) / activity.getDuration()) > ACTIVITY_STATUS_LIMIT) {
					activity.setMode(PlannedActivityMode.POSITIVE);
				}
				else {
					activity.setMode(PlannedActivityMode.NEGATIVE);
				}
				
				result.add(activity);
			}
		}
		
		return result;
	}
	
	private void updatePlannedActivity(PlannedActivity item) {
		int position = -1;
		for (int i = 0; i < activities.size(); i++) {
			if (activities.get(i).getActivityItem().getId() == item.getActivityItem().getId()) {
				position = i;
				break;
			}
		}
		
		if (position < 0) {
			// Add new object to the collection
			activities.add(item);
		}
		else {
			// Update object 
			activities.set(position, item);
		}
		this.onResume();
		Toast.makeText(this, item.getActivityItem().getName() + " was successfully saved", Toast.LENGTH_SHORT).show();
	}
	
	private void deletePlanendActivity(int position) {
		boolean deleted = dbManager.deletePlannedActivity(activities.get(position));
		if (deleted) {
			PlannedActivity deletedActivity = activities.get(position);
			activities.remove(position);
			refreshAdapter();
			
			Toast.makeText(this, deletedActivity.getActivityItem().getName() + " was successfully deleted", Toast.LENGTH_SHORT).show();
		}
	}
	
	private class PlannedActivityAdapter extends ArrayAdapter<PlannedActivity> {
		
        private ArrayList<PlannedActivity> items;

        public PlannedActivityAdapter(Context context, int textViewResourceId, ArrayList<PlannedActivity> items) {
                super(context, textViewResourceId, items);
                this.items = items;
        }
        
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
                
        	View v = convertView;
                if (v == null) {
                    LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    v = vi.inflate(R.layout.item_row, null);
                }
                
                PlannedActivity p = items.get(position);

                if (p != null) {
                	TextView tvName = (TextView)v.findViewById(R.id.itemName);
                    TextView tvInfo = (TextView)v.findViewById(R.id.itemInfo);
                    TextView tvStatus = (TextView)v.findViewById(R.id.itemStatus);
                    ProgressBar progressBar = (ProgressBar)v.findViewById(R.id.itemProgressBar);
                    
                   
                    int spentTimeInMins = dbManager.getTimeSpentForPlannedActivity(p);
                    String restTime = calculateRestTime(p, spentTimeInMins);
                    double current = ((double)spentTimeInMins) / 60.0;
                    Double ddd = (double) ((current / p.getDuration()) * 100);
                    DecimalFormat twoDForm = new DecimalFormat("#.##");
                    ddd = Double.valueOf(twoDForm.format(ddd));
                    double progress = ddd.intValue();

                    progressBar.setProgress((int)progress);
                    if (tvName != null) {
                    	if (comeFromNotification) {
                    		int iconId = 0;
                    		if (p.getMode() == PlannedActivityMode.POSITIVE) {
                    			iconId = R.drawable.ic_up;
                    		}
                    		else {
                    			iconId = R.drawable.ic_down;
                    		}
                    		Bitmap icon = BitmapFactory.decodeResource(getResources(), iconId);
                        	Drawable img = getResources().getDrawable(iconId);
                        	img.setBounds(0, 0, icon.getWidth(), icon.getHeight());
                        	tvName.setCompoundDrawables(img, null, null, null);
                    	}
                    	
                    	tvName.setText(p.getActivityItem().getName());
                	}
                    if (tvInfo != null) {
                    	tvInfo.setText(p.getActivityItem().getCategory());
                    }
                    if (tvStatus != null) {
                    	tvStatus.setText("Duration: " + String.valueOf(p.getDuration()) + "h\t " +
                    			("Remaining time: " + String.valueOf(restTime)));
                    }
                }
                return v;
        }
	}

	public String calculateRestTime(PlannedActivity p, int spentTimeInMins) {
		
		String restTime = null;
        
        if(spentTimeInMins > p.getDuration() * 60) {
        	return "0 h";
        }

    	if(spentTimeInMins == 0) {
    		restTime = p.getDuration() + "h";
    	}
    	else {
    		int restTimeInMinutes = (int) (p.getDuration() * 60 - spentTimeInMins);
    		int hours = restTimeInMinutes / 60;
			int minutes = restTimeInMinutes % 60;
			if(hours == 0) {
				restTime = minutes + " min";
			}
			else {
				if(minutes != 0)
					restTime = hours + " h, " + minutes + " min";
				else 
					restTime = hours + "h";
			}
    	}
    	return restTime;
	}
}
